//
//  XMGBaseTopiceViewController.m
//  BuDeJie19
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

#import "XMGBaseTopiceViewController.h"
#import "XMGTopicCell.h"
#import "XMGNewViewController.h"
#import <MJExtension/MJExtension.h>
#import "XMGTopicViewModel.h"
#import <MJRefresh/MJRefresh.h>
#import "UIView+Fetch.h"

static NSString * const ID = @"cell";
@interface XMGBaseTopiceViewController ()
@property (nonatomic, strong) NSMutableArray *topicsVM;
@property (nonatomic, strong) NSString *maxtime;
@property (nonatomic, weak) AFHTTPSessionManager *mgr;
@end

@implementation XMGBaseTopiceViewController

- (AFHTTPSessionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [AFHTTPSessionManager xmg_manager];
    }
    return _mgr;
}

- (NSMutableArray *)topicsVM
{
    if (_topicsVM == nil) {
        _topicsVM = [NSMutableArray array];
    }
    return _topicsVM;
}

- (void)reload
{
    // 谁刷新数据
    // 判断谁在窗口上，谁就显示
    // iOS10,不能通过self.view.window，判断当前控件是否在窗口上
    // 获取窗口下的tableView
    UITableView *tableView = [[UIApplication sharedApplication].keyWindow fetchTableView];
    
    [tableView.mj_header beginRefreshing];
    
//    if (self.view.window) { // 只要一个View在窗口上，肯定能拿到窗口
//        
//        [self.tableView.mj_header beginRefreshing];
//        
//    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    
    // 只要通过registerClass，TableViewCell就是通过initWithStyle
    [self.tableView registerClass:[XMGTopicCell class] forCellReuseIdentifier:ID];
    
    // 添加上下拉刷新
    [self setupRefreshVeiw];
    
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(99, 0, 49, 0);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:@"repeatClickTab" object:nil];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupRefreshVeiw
{
    // 添加下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 根据拖拽，自动显示下拉控件
    header.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = header;
    
    // 上拉刷新
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 自动根据有无数据，判断上拉控件是否完全显示
    footer.automaticallyHidden = YES;
    
    self.tableView.mj_footer = footer;
    
}

#pragma mark - 加载更多数据
- (void)loadMoreData
{
    
    // 取消之前请求
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSString *a = @"list";
    // 判断是精华还是新帖
    if ([self.parentViewController isKindOfClass:[XMGNewViewController class]]) {
        a = @"newlist";
    }
    
    parameters[@"a"] = a;
    parameters[@"c"] = @"data";
    parameters[@"maxtime"] = _maxtime;
    parameters[@"type"] = self.type;
    
    [self.mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self.tableView.mj_footer endRefreshing];
        
        // 保存下一页最大ID
        _maxtime =  responseObject[@"info"][@"maxtime"];
        
        // 字典数组 转 模型数组
        NSArray *topics = [XMGTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 计算topView尺寸 =》 cell尺寸
        // 模型转视图模型
        for (XMGTopicItem *item in topics) {
            
            XMGTopicViewModel *vm = [[XMGTopicViewModel alloc] init];
            // 计算cell高度和子控件尺寸
            vm.item = item;
            [self.topicsVM addObject:vm];
        }
        
        // 刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

// 请求数据
- (void)loadNewData
{
    // 取消之前请求
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *a = @"list";
    // 判断是精华还是新帖
    if ([self.parentViewController isKindOfClass:[XMGNewViewController class]]) {
        a = @"newlist";
    }
    parameters[@"a"] = a;
    parameters[@"c"] = @"data";
    parameters[@"type"] = self.type;
    
    [self.mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        // 结束头部刷新
        [self.tableView.mj_header endRefreshing];
        
        // 保存下一页最大ID
        _maxtime =  responseObject[@"info"][@"maxtime"];
        
        // 字典数组 转 模型数组
        NSArray *topics = [XMGTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        
        // 计算topView尺寸 =》 cell尺寸
        // 模型转视图模型
        NSMutableArray *arr = [NSMutableArray array];
        for (XMGTopicItem *item in topics) {
            
            XMGTopicViewModel *vm = [[XMGTopicViewModel alloc] init];
            // 计算cell高度和子控件尺寸
            vm.item = item;
            [arr addObject:vm];
        }
        
        self.topicsVM = arr;
        
        // 刷新表格
        [self.tableView reloadData];
        
        [responseObject writeToFile:@"/Users/xmg5/Desktop/课堂共享/03-项目/1026/代码/08-全部主题Cell搭建/topic.plist" atomically:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}



#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _topicsVM.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMGTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    cell.vm = _topicsVM[indexPath.row];
    
    return cell;
}

// 返回cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [_topicsVM[indexPath.row] cellH] + 10;
}

@end
